package vincent.com.layouttest.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import vincent.com.layouttest.R;

/**
 * Created by zhengwenchen on 2017/1/6.
 */

public class P2GainModeView extends ImageView{
    public static final String ACTION_CHANGE_GAIN_MODE_COMPLETED = "com.kugou.p2player.change_gain_mode_completed";

    private boolean mAttached = false;
    private String currentGainMode = null;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(ACTION_CHANGE_GAIN_MODE_COMPLETED.equals(action)){
                String change_to = intent.getStringExtra("current");
                Log.i("czw", "增益改变---->" + change_to);

                currentGainMode = change_to;
                updateIcon();
            }
        }
    };

    public P2GainModeView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public P2GainModeView(Context context) {
        this(context, null);
    }

    public P2GainModeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void updateIcon(){
        setVisibility(View.VISIBLE);
        if("0".equals(currentGainMode)){
            setImageResource(R.drawable.gain_low);
        }else if("1".equals(currentGainMode)){
            setImageResource(R.drawable.gain_mid);
        }else if("2".equals(currentGainMode)){
            setImageResource(R.drawable.gain_high);
        }else{
            setVisibility(View.GONE);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if(!mAttached){
            mAttached = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_CHANGE_GAIN_MODE_COMPLETED);

            getContext().registerReceiver(mReceiver, filter);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mAttached){
            getContext().unregisterReceiver(mReceiver);
            mAttached = false;
        }
    }

    public String getCurrentGainMode(){
        return currentGainMode;
    }
}
